package mail

import (
	"bytes"
	"encoding/json"
	"errors"
	"fmt"
	"io/ioutil"
	"math/rand"
	"net/http"
)

// 邮件发送器结构体
type EmailSender struct {
	Url       string `json:"url"`
	Accesskey string `json:"accesskey"`
	Secretkey string `json:"secretkey"`
}

type ResponseBody struct {
	Result int    `json:"result"`
	ErrMsg string `json:"errMsg"`
}

// 生成随机数
func getRandom() int {
	return 100000 + rand.Intn(900000)
}

// 发送curl post请求
func sendCurlPost(url string, data interface{}) (string, error) {
	// 将data转换为json字节数组
	jsonData, err := json.Marshal(data)
	if err != nil {
		return "", err
	}

	// 创建http请求
	req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
	if err != nil {
		return "", err
	}

	// 设置请求头
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("Content-Length", fmt.Sprintf("%d", len(jsonData)))

	// 发送请求
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()

	// 读取响应内容
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}

	var response ResponseBody
	err = json.Unmarshal(body, &response)
	if err != nil {
		return "", err
	}
	if response.Result != 0 {
		return "", errors.New(response.ErrMsg)
	}
	return string(body), nil
}

// 普通单发邮件
//func SendSingleEmail(typeNum int, toEmail string, fromEmail string, needToReply bool, replyEmail string, fromAlias string, htmlBody string, subject string, ext string) (string, error) {
//	// 生成随机数和时间戳
//	random := getRandom()
//	curTime := time.Now().Unix()
//
//	// 计算签名
//	sig := fmt.Sprintf("%x", sha256.Sum256([]byte(fmt.Sprintf("secretkey=%s&random=%d&time=%d&fromEmail=%s", global.EmailConfig.Secretkey, random, curTime, fromEmail))))
//
//	// 构建请求数据
//	data := map[string]interface{}{
//		"sig":         sig,
//		"ext":         ext,
//		"replyEmail":  replyEmail,
//		"fromAlias":   fromAlias,
//		"htmlBody":    htmlBody,
//		"needToReply": needToReply,
//		"subject":     subject,
//		"clickTrace":  "0",
//		"time":        curTime,
//		"type":        typeNum,
//		"toEmail":     toEmail,
//		"fromEmail":   fromEmail,
//	}
//
//	// 发送请求
//	wholeUrl := fmt.Sprintf("%s?accesskey=%s&random=%d", "https://live.moduyun.com/directmail/v1/singleSendMail", global.EmailConfig.Accesskey, random)
//	result, err := sendCurlPost(wholeUrl, data)
//	if err != nil {
//		return "", err
//	}
//
//	return result, nil
//}
